//
//  AppDelegate.m
//  GIFShow
//
//  Created by lanou11air029 on 15/3/27.
//  Copyright (c) 2015年 CK. All rights reserved.
//

#import "AppDelegate.h"
#import "RootTabController.h"
#import "MySettingOptions.h"
#import "XGPush.h"
#import "XGSetting.h"
#import "UMSocial.h"
#import "UMSocialQQHandler.h"
#import "UMSocialSinaHandler.h"
#import "UMSocialWechatHandler.h"
#import "UMFeedback.h"
#import "UMessage.h"
@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    [self shareSetting];
    NSUserDefaults * userDefaultSetting = [NSUserDefaults standardUserDefaults];
    BOOL installed = [userDefaultSetting boolForKey:@"haveinstalled"];
    if (installed) {
        UIViewController * vc = [[UIViewController alloc]init];
        UIImageView * backImageView = [[UIImageView alloc]initWithFrame:vc.view.bounds];
        backImageView.image = [UIImage imageNamed:@"LaunchImage"];
        [vc.view addSubview:backImageView];
        vc.view.backgroundColor = [UIColor clearColor];
        UIImageView * imageView = [[UIImageView alloc]initWithFrame:vc.view.bounds];
        imageView.image = [UIImage imageNamed:@"comein"];
        //    imageView.alpha = 1;
        imageView.alpha = 0;
        vc.view.backgroundColor = [UIColor clearColor];
        [vc.view addSubview:imageView];
        self.window.rootViewController = vc;
        [UIView animateWithDuration:0.67 animations:^{
            imageView.alpha = 0.8;
        } completion:^(BOOL finished) {
            RootTabController * rootTabVC = [[RootTabController alloc]init];
            self.window.rootViewController = rootTabVC;
        }];
    }else{
        UIViewController * loadVC = [[UIViewController alloc]init];
        UIScrollView * loadSCV = [[UIScrollView alloc]initWithFrame:loadVC.view.bounds];
        loadSCV.contentSize = CGSizeMake(loadSCV.frame.size.width*3, loadSCV.frame.size.height);
        for (int i = 0; i<3; i++) {
            UIImageView * imageView = [[UIImageView alloc]initWithFrame:CGRectMake(i*loadVC.view.frame.size.width, 0, loadVC.view.frame.size.width, loadVC.view.frame.size.height)];
            imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"%d.jpg",i+1]];
            [loadSCV addSubview:imageView];
        }
        [loadVC.view addSubview:loadSCV];
        UIButton * clickIn = [UIButton buttonWithType:UIButtonTypeSystem];
        self.window.rootViewController = loadVC;
        [clickIn setTitle:@"立即进入体验" forState:UIControlStateNormal];
        clickIn.backgroundColor = [UIColor redColor];
        clickIn.frame = CGRectMake(loadSCV.contentSize.width - loadSCV.frame.size.width*0.5-50, loadSCV.frame.size.height*0.5, 100, 40);
        [loadSCV addSubview:clickIn];
        loadSCV.pagingEnabled = YES;
        [clickIn addTarget:self action:@selector(didClickInButtonAction) forControlEvents:UIControlEventTouchUpInside];
        
        [userDefaultSetting setBool:YES forKey:@"haveinstalled"];
    }

    
    // nav颜色
    
    [[UIBarButtonItem appearance] setTintColor:[UIColor whiteColor]];
    
//    [[UIBarButtonItem appearance]setTintColor:[UIColor colorWithRed:0.05 green:0.8 blue:0.02 alpha:0.9]];

//    MySettingOptions * myOptions = [MySettingOptions defaultOptions];
    NSLog(@"%@",NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES));
    float systemVersion = [UIDevice currentDevice].systemVersion.floatValue;
    if (systemVersion >= 8.0) {
        [self registerForiOS8];
    }else{
        [self registerForEarilyiOS];
    }
    [UMessage setLogEnabled:NO];
    
    //关闭状态时点击反馈消息进入反馈页
    NSDictionary *notificationDict = [launchOptions valueForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    [UMFeedback didReceiveRemoteNotification:notificationDict];
//    UIUserNotificationSettings * setting = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound) categories:nil];
//    [[UIApplication sharedApplication] registerUserNotificationSettings:setting];
//    [[UIApplication sharedApplication]registerForRemoteNotifications];
    [[UMFeedback sharedInstance] setFeedbackViewController:nil shouldPush:YES];
    return YES;
}
-(void)didClickInButtonAction{
    RootTabController * rootTabVC = [[RootTabController alloc]init];
    self.window.rootViewController = rootTabVC;
}
// 友盟
#pragma mark -UMSocialShare
-(void)shareSetting{
    // 友盟
    [UMSocialData setAppKey:UMengAppKey];
    [UMFeedback setAppkey:UMengAppKey];
    // qq
    [UMSocialQQHandler setQQWithAppId:@"1104458903" appKey:@"c7394704798a158208a74ab60104f0ba" url:@"https://itunes.apple.com/us/app/ck-gao-xiaogif-xiu-gao-xiao/id982491452?l=zh&ls=1&mt=8"];
    // sina
    [UMSocialSinaHandler openSSOWithRedirectURL:@"http://sns.whalecloud.com/sina2/callback"];
    // webchat 微信
    [UMSocialWechatHandler setWXAppId:@"wxa6e864daefa5fd1f" appSecret:@"2785348e69b8ae704b73565ff31477a3" url:@"https://itunes.apple.com/us/app/ck-gao-xiaogif-xiu-gao-xiao/id982491452?l=zh&ls=1&mt=8"];

    //AppID：wxa6e864daefa5fd1f
//    AppSecret：2785348e69b8ae704b73565ff31477a3
    // qqwb

    
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    return  [UMSocialSnsService handleOpenURL:url];
}
//- (BOOL)application:(UIApplication *)application
//            openURL:(NSURL *)url
//  sourceApplication:(NSString *)sourceApplication
//         annotation:(id)annotation
//{
//    return  [UMSocialSnsService handleOpenURL:url];
//}
// 若你除了使用我们SDK外，还用了其他SDK，需要重写此回调方法的，可以参考下面的写法：

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    BOOL result = [UMSocialSnsService handleOpenURL:url];
    if (result == FALSE) {
        //调用其他SDK，例如新浪微博SDK等
    }
    return result;
}
// 推送设置

-(void)registerForiOS8{
        //register remoteNotification types
        UIMutableUserNotificationAction *action1 = [[UIMutableUserNotificationAction alloc] init];
        action1.identifier = @"action1_identifier";
        action1.title=@"Accept";
        action1.activationMode = UIUserNotificationActivationModeForeground;//当点击的时候启动程序
        
        UIMutableUserNotificationAction *action2 = [[UIMutableUserNotificationAction alloc] init];  //第二按钮
        action2.identifier = @"action2_identifier";
        action2.title=@"Reject";
        action2.activationMode = UIUserNotificationActivationModeBackground;//当点击的时候不启动程序，在后台处理
        action2.authenticationRequired = YES;//需要解锁才能处理，如果action.activationMode = UIUserNotificationActivationModeForeground;则这个属性被忽略；
        action2.destructive = YES;
        
        UIMutableUserNotificationCategory *categorys = [[UIMutableUserNotificationCategory alloc] init];
        categorys.identifier = @"category1";//这组动作的唯一标示
        [categorys setActions:@[action1,action2] forContext:(UIUserNotificationActionContextDefault)];
        UIUserNotificationSettings *userSettings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert
                                                                                     categories:[NSSet setWithObject:categorys]];
        
        [UMessage registerRemoteNotificationAndUserNotificationSettings:userSettings];

}

-(void)registerForEarilyiOS{
    [[UIApplication sharedApplication]registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeBadge|UIRemoteNotificationTypeSound)];
}

-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
    [XGPush startApp:kACCESSID appKey:kACCESSKEY];

    NSString * deviceStr = [XGPush registerDevice:deviceToken];
    [UMessage registerDeviceToken:deviceToken];
    NSLog(@"umeng message alias is: %@", [UMFeedback uuid]);
    [UMessage addAlias:[UMFeedback uuid] type:[UMFeedback messageType] response:^(id responseObject, NSError *error) {
        if (error != nil) {
            NSLog(@"%@", error);
            NSLog(@"%@", responseObject);
        }
    }];
    
}
// 接收推送
//-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{
//    
//}
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
    [UMFeedback didReceiveRemoteNotification:userInfo];

}
-(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
    NSLog(@"error = %@",error);
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {

    [[NSNotificationCenter defaultCenter] postNotificationName:@"becomeActive" object:nil userInfo:nil];
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    [self saveContext];
}

#pragma mark - Core Data stack

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (NSURL *)applicationDocumentsDirectory {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "com.chenkai.GIFShow" in the application's documents directory.
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSManagedObjectModel *)managedObjectModel {
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"GIFShow" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it.
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    // Create the coordinator and store
    
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"GIFShow.sqlite"];
    NSError *error = nil;
    NSString *failureReason = @"There was an error creating or loading the application's saved data.";
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        // Report any error we got.
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonErrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
    return _persistentStoreCoordinator;
}


- (NSManagedObjectContext *)managedObjectContext {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] init];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    return _managedObjectContext;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = nil;
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}

@end
